package user

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
	"zhuandan/utils"
)

func Classifys(ctx *gin.Context) {
	var classfify []models.Classify
	data_source.Db.Find(&classfify)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    classfify,
		"msg":     "ok",
	})
	return
}

type ProcureBody struct {
	ID            int64   `gorm:"column:id" json:"id"`
	Uid           int64   `gorm:"column:uid" json:"uid"`
	Province      string  `gorm:"column:province" json:"province"` //省份
	Provinceid    int64   `gorm:"column:provinceid" json:"provinceid"`
	City          string  `gorm:"column:city" json:"city"`
	Cityid        int64   `gorm:"column:cityid" json:"cityid"`
	County        string  `gorm:"column:county" json:"county"`
	Countyid      int64   `gorm:"column:countyid" json:"countyid"`
	Title         string  `gorm:"column:title" json:"title"`     //  标题
	Content       string  `gorm:"column:content" json:"content"` //  描述
	Num           int64   `gorm:"column:num" json:"num"`
	Price         float64 `gorm:"column:price" json:"price"`
	Name          string  `gorm:"column:name" json:"name"`
	Phone         string  `gorm:"column:phone" json:"phone"`
	Buynum        int64   `gorm:"column:buynum" json:"buynum"` //  已经售出
	Classifyid    int64   `gorm:"column:classifyid" json:"classifyid"`
	Classifytitle string  `gorm:"column:classifytitle" json:"classifytitle"`
	Classifyvalue string  `gorm:"column:classifyvalue" json:"classifyvalue"`
	Image         string  `gorm:"column:image" json:"image"`
	Audio         string  `gorm:"column:audio" json:"audio"`
}

func Tuisong(ctx *gin.Context) {
	Appinfosend("585447")
}

func Procureadd(ctx *gin.Context) {
	request := ProcureBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	province := request.Province
	provinceid := request.Provinceid
	city := request.City
	cityid := request.Cityid
	county := request.County
	countyid := request.Countyid
	title := request.Title
	content := request.Content
	num := request.Num
	price := request.Price
	name := request.Name
	phone := request.Phone
	classifyid := request.Classifyid
	classifytitle := request.Classifytitle
	classifyvalue := request.Classifyvalue
	image := request.Image
	audio := request.Audio

	dqtime := time.Now().Unix() - 86400*60
	var procuerinfo models.Procure
	if len(phone) < 11 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "手机号不正确",
		})
		return
	}
	if len(phone) > 11 {
		data_source.Db.Where("phone = ?", phone[:11]).Where("addtime > ?", dqtime).First(&procuerinfo)
	} else if len(phone) == 11 {
		data_source.Db.Where("phone = ?", phone).Where("addtime > ?", dqtime).First(&procuerinfo)
	}

	if procuerinfo.ID > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "一个手机号两个月内只能发布一次",
		})
		return
	}

	if len(phone) != 11 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "手机号不正确",
		})
		return
	}

	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	//if user.Phone == "" {
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    300,
	//		"error":   1,
	//		"success": 400,
	//		"data":    "on",
	//		"msg":     "请绑定手机号",
	//	})
	//	return
	//}

	//if user.Identity == 2 {
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    300,
	//		"error":   1,
	//		"success": 400,
	//		"data":    "on",
	//		"msg":     "该账号禁止发布，如果有疑问请联系客服",
	//	})
	//	return
	//}

	pro := models.Procure{
		Uid:           uid,
		Province:      province,
		Provinceid:    provinceid,
		City:          city,
		Cityid:        cityid,
		County:        county,
		Countyid:      countyid,
		Title:         title,
		Content:       content,
		Num:           num,
		Price:         price,
		Name:          name,
		Phone:         phone,
		Classifyid:    classifyid,
		Classifyvalue: classifyvalue,
		Classifytitle: classifytitle,
		Addtime:       time.Now().Unix(),
		State:         1,
		Fbrphone:      user.Phone,
		Fasong:        1,
		Image:         image,
		Audio:         audio,
		Jieshu:        1,
	}
	data_source.Db.Create(&pro)

	//info := models.Infosjb{
	//	Classifysjbid: classifyid,
	//	Typesjbid:     3,
	//	Provinceid:    provinceid,
	//	Province:      province,
	//	Cityid:        cityid,
	//	Cityname:      city,
	//	Title:         title,
	//	Content:       content,
	//	Price:         price,
	//	Username:      name,
	//	Phone:         phone,
	//	Num:           num,
	//	Addtime:       time.Now().Unix(),
	//	Procureid:     pro.ID,
	//}
	//data_source.Db.Create(&info)
	//url := "http://h.suishilian.com/detail/" + utils.Int64string(pro.ID)
	//var areaarr []string
	//var areacodearr []string
	//areaarr = append(areaarr, province)
	//areaarr = append(areaarr, city)
	//areaarr = append(areaarr, county)
	//areacodearr = append(areacodearr, utils.Int64string(provinceid))
	//areacodearr = append(areacodearr, utils.Int64string(cityid))
	//areacodearr = append(areacodearr, utils.Int64string(countyid))
	//
	//area := strings.Join(areaarr, " ")
	//areacode := strings.Join(areacodearr, ",")
	//
	//var classify models.Classify
	//data_source.Db.Where("id = ?", classifyid).First(&classify)
	//
	////title1 := "转单:" + title
	//res := Appinfomodify(classify.Value, title, name, phone, utils.Int64string(num), content, "1", area, areacode, url, price)
	//if res.InfoId != "" {
	//	data_source.Db.Model(&models.Procure{}).Where("id = ?", pro.ID).Update("info_id", res.InfoId)
	//	//Appinfosend(res.InfoId)
	//} else {
	//	data_source.Db.Where("id = ?", pro.ID).Delete(&models.Procure{})
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    400,
	//		"error":   0,
	//		"success": 400,
	//		"data":    "发布失败",
	//		"msg":     "发布失败",
	//	})
	//	return
	//}
	var prolist []models.Procure
	data_source.Db.Select("id").Where("uid = ?", uid).Find(&prolist)
	if len(prolist) > 0 {
		userup := models.User{
			Fbnum:  user.Fbnum + 1,
			Fbtime: time.Now().Unix(),
		}
		data_source.Db.Where("id = ?", uid).Updates(&userup)
	} else {
		userup := models.User{
			Fbnum:     user.Fbnum + 1,
			Fbtime:    time.Now().Unix(),
			Fbinttime: time.Now().Unix(),
		}
		data_source.Db.Where("id = ?", uid).Updates(&userup)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procurezf(ctx *gin.Context) {
	request := ProcureBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	id := request.ID
	zf := models.Zhuanfalog{
		Uid:       uid,
		Procureid: id,
		Addtime:   time.Now().Unix(),
	}
	data_source.Db.Create(&zf)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Procureaddceshi(ctx *gin.Context) {
	request := ProcureBody{}
	ctx.ShouldBind(&request)
	phone := request.Phone

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    phone[:11],
		"msg":     "ok",
	})
	return
}
func Fabulogadd(ctx *gin.Context) {
	request := ProcureBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid

	pro := models.Fabulog{
		Uid:     uid,
		Addtime: time.Now().Unix(),
	}
	data_source.Db.Create(&pro)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Appinfosend(info_id string) (data Responsewxusermodify) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_info_send"}, "info_id": {info_id}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxusermodify{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type Responsewxusermodify struct {
	Status int64  `json:"status"`
	Error  string `json:"error"`
	InfoId string `json:"info_id"`
}

func Appinfomodify(itemtype, title, contact_name, contact_tel, num, content, status, area, area_code, other_url string, money float64) (data Responsewxusermodify) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_info_modify"}, "item_type": {itemtype}, "title": {title}, "contact_name": {contact_name}, "contact_tel": {contact_tel}, "num": {num}, "content": {content}, "status": {status}, "area": {area}, "area_code": {area_code}, "other_url": {other_url}, "source_type": {"转单宝"}, "total": {"4"}, "price": {utils.FloatToStr64(money)}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxusermodify{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type ProcureRBody struct {
	Data       []models.Procure `json:"data"`
	PageNo     int              `json:"pageNo"`
	PageSize   int              `json:"pageSize"`
	TotalCount int64            `json:"totalCount"`
	TotalPage  int64            `json:"totalPage"`
}

type ProcuresBody struct {
	ID             int64  `json:"id" from:"id"`
	Uid            int64  `json:"uid" from:"uid"`
	Page           int    `json:"pageNo" from:"pageNo"`
	Pagesize       int    `json:"pageSize" from:"pageSize"`
	Procuresid     int64  `json:"procuresid" from:"procuresid"`
	State          int64  `json:"state" from:"state"`
	Procureorderid int64  `json:"procureorderid" from:"procureorderid"`
	Provinceid     int64  `json:"provinceid" from:"provinceid"`
	Keyword        string `json:"keyword" from:"keyword"`
	Beizhu         string `gorm:"column:beizhu" json:"beizhu"`
	Status         int64  `gorm:"column:status" json:"status"`
	Laiyuan        int64  `gorm:"column:laiyuan" json:"laiyuan"`
}

func Procurelist(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	provinceid := request.Provinceid
	keyword := request.Keyword
	//laiyuan := request.Laiyuan
	uid := request.Uid
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	//var count int64
	var users []models.Procure
	res := data_source.Db.Select("id,title,province,city,county,content,num,buynum,addtime,classifyid")
	if provinceid > 0 {
		res = res.Where("provinceid = ?", provinceid)
	}
	if keyword != "" {
		res = res.Where("title like ? or content like ?", "%"+keyword+"%", "%"+keyword+"%")
	}
	if uid > 0 {
		//res = res.Where("fasong > 1")
		var tuisongs []models.Tuisongshezhi
		data_source.Db.Where("state = 1").Where("uid = ?", uid).Find(&tuisongs)
		var procureidarr []string
		var classifyidarr []string
		for _, t := range tuisongs {
			procureidarr = append(procureidarr, utils.Int64string(t.Provinceid))
			classifyidarr = append(classifyidarr, utils.Int64string(t.Classifyid))
		}
		res = res.Where("provinceid in (?)", procureidarr).Where("classifyid in (?)", classifyidarr)
		var user models.User
		data_source.Db.Where("id = ?", uid).First(&user)
		if user.Ifbuy == 1 && user.Bnendtime < time.Now().Unix() {
			res = res.Where("laiyuanval != ?", "第三方")
		}
		if user.Bnendtime > time.Now().Unix() {
			res = res.Where("fasong > 1")
		} else {
			res = res.Where("fasong = 3")
		}

	}

	//res.Model(&models.Procure{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("addtime desc").Find(&users)
	data := ProcureRBody{
		Data: users,
		//PageNo:     currentPage,
		//PageSize:   pageSize,
		//TotalCount: count,
		//TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procures(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Procure
	res := data_source.Db.Where("uid = ?", uid)
	res.Model(&models.Procure{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procurebeizhu(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	beizhu := request.Beizhu
	data_source.Db.Model(&models.Procureorder{}).Where("id = ?", id).Update("beizhu", beizhu)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Procureinfo(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	procuresid := request.Procuresid

	var procure models.Procure
	data_source.Db.Where("id = ?", procuresid).First(&procure)
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	if user.Bnendtime > time.Now().Unix() && user.Bninttime < time.Now().Unix() {
		var baonian models.Baonian
		data_source.Db.Debug().Where("uid = ?", uid).Where("classifyid = ?", procure.Classifyid).First(&baonian)
		if baonian.ID > 0 {
			procure.Buy = 2
		} else {
			var pror models.Procureorder
			data_source.Db.Where("procureid = ?", procuresid).Where("uid = ?", uid).Where("status != 4").First(&pror)
			if pror.ID == 0 {
				procure.Buy = 1
				procure.Phone = MaskPhone(procure.Phone)
			} else {
				procure.Buy = 2
			}
		}
	} else {
		procure.Buy = 1
		var pror models.Procureorder
		data_source.Db.Where("procureid = ?", procuresid).Where("uid = ?", uid).Where("status != 4").First(&pror)
		if pror.ID == 0 {
			procure.Buy = 1
			procure.Phone = MaskPhone(procure.Phone)
		} else {
			procure.Buy = 2
		}
		if uid == 0 {
			procure.Phone = MaskPhone(procure.Phone)
		}
		if procure.Buynum == 0 {
			procure.Phone = MaskPhone(procure.Phone)
		}
		if procure.Buy == 1 {
			procure.Phone = MaskPhone(procure.Phone)
		}
	}

	if uid > 0 {
		now := time.Now()
		year, month, day := now.Date()
		// 今日日期
		today := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
		procurelog := models.Procurelog{
			Uid:       uid,
			Addtime:   time.Now().Unix(),
			Num:       1,
			Day:       today.Unix(),
			Procureid: procuresid,
			Title:     procure.Title,
			Userprice: user.Price,
		}
		data_source.Db.Create(&procurelog)
	}
	var procures []models.Procure
	data_source.Db.Where("classifyid = ?", procure.Classifyid).Where("fasong > 1").Limit(10).Order("addtime desc").Find(&procures)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    procure,
		"list":    procures,
		"msg":     "ok",
	})
	return
}
func MaskPhone(phone string) string {
	if len(phone) <= 10 {
		return phone
	}
	return phone[:3] + "********"
}
func Procurebuy(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	procuresid := request.Procuresid
	state := request.State
	if state == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请选择独占或购买一条",
		})
		return
	}
	var procure models.Procure
	data_source.Db.Where("id = ?", procuresid).First(&procure)

	var duli []models.Classifyduli
	data_source.Db.Find(&duli)

	var ifduli int64
	ifduli = 1
	for _, d := range duli {
		if d.Classifyid == procure.Classifyid {
			ifduli = 2
		}
	}
	if ifduli == 1 {
		if procure.Buynum >= 4 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "已经被买完了",
			})
			return
		}
	}
	if ifduli == 2 {
		if state == 2 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "该信息只能购买一条",
			})
			return
		}
	}
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	var price float64
	var userprice float64

	userprice = user.Price

	price = procure.Price
	var status int64
	if procure.Uid > 1000 {
		status = 1
	} else {
		status = 2
	}
	if user.Bnendtime > time.Now().Unix() {
		if state == 2 {
			buyordernumbn := 4 - procure.Buynum
			price = price * float64(buyordernumbn)
			if userprice < price {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    400,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "余额不足",
				})
				return
			}

			prorder := models.Procureorder{
				Uid:        uid,
				Addtime:    time.Now().Unix(),
				Procureid:  procuresid,
				Num:        buyordernumbn,
				Price:      procure.Price,
				Phone:      user.Phone,
				Status:     status,
				Fbuid:      procure.Uid,
				Title:      procure.Title,
				Updatetime: time.Now().Unix(),
			}
			data_source.Db.Create(&prorder)
			procureupdatadz := models.Procure{
				Buynum: 4,
			}
			data_source.Db.Where("id = ?", procuresid).Updates(&procureupdatadz)

			data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("price", userprice-price)
			userpricenew := models.Userpricenew{
				Uid:     uid,
				Addtime: time.Now().Unix(),
				State:   2,
				Price:   price,
				Title:   "购买信息" + procure.Title,
				Dqprice: userprice - price,
			}
			data_source.Db.Create(&userpricenew)

			if user.Pid > 0 {
				var userp models.User
				data_source.Db.Where("id = ?", user.Pid).First(&userp)
				if userp.Xiaoshoutuiguan == 2 {
					var tuiguang models.Tuiguang
					data_source.Db.Where("id = 2").First(&tuiguang)
					tcprice := price * float64(tuiguang.Bfb) / 100
					userpup := models.User{
						Tcprice: userp.Tcprice + tcprice,
						Price:   userp.Price + tcprice,
					}
					data_source.Db.Where("id = ?", user.Pid).Updates(&userpup)
					uprice := models.Userpricenew{
						Uid:     user.Pid,
						Price:   tcprice,
						State:   1,
						Addtime: time.Now().Unix(),
						Title:   "下级用户购买信息收到提成",
						Dqprice: userp.Price,
					}
					data_source.Db.Create(&uprice)
				}

			}

			if status == 1 {
				var fbruser models.User
				data_source.Db.Where("id = ?", procure.Uid).First(&fbruser)
				data_source.Db.Model(&models.User{}).Where("id = ?", procure.Uid).Update("dsx", fbruser.Dsx+price)

				userdsx := models.Userdsx{
					Uid:     procure.Uid,
					Price:   price,
					Title:   "用户购买,增加待生效金额",
					Addtime: time.Now().Unix(),
					Zqprice: fbruser.Dsx,
				}
				data_source.Db.Create(&userdsx)
				currentTime := time.Now()
				year, month, day := currentTime.Date()
				shijian := utils.Int64string(int64(year)) + "年" + utils.Int64string(int64(month)) + "月" + utils.Int64string(int64(day)) + "日"
				Buychenggong(fbruser.RoutineOpenid, procure.Title, shijian, utils.Int64string(buyordernumbn))
			}
		} else {
			buyordernumbn := 1
			price = price * float64(buyordernumbn)
			if userprice < price {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    400,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "余额不足",
				})
				return
			}

			prorder := models.Procureorder{
				Uid:        uid,
				Addtime:    time.Now().Unix(),
				Procureid:  procuresid,
				Num:        int64(buyordernumbn),
				Price:      procure.Price,
				Phone:      user.Phone,
				Status:     status,
				Fbuid:      procure.Uid,
				Title:      procure.Title,
				Updatetime: time.Now().Unix(),
			}
			data_source.Db.Create(&prorder)
			procureupdatadz := models.Procure{
				Buynum: procure.Buynum + 1,
			}
			data_source.Db.Where("id = ?", procuresid).Updates(&procureupdatadz)

			data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("price", userprice-price)
			userpricenew := models.Userpricenew{
				Uid:     uid,
				Addtime: time.Now().Unix(),
				State:   2,
				Price:   price,
				Title:   "购买信息" + procure.Title,
				Dqprice: userprice - price,
			}
			data_source.Db.Create(&userpricenew)

			if user.Pid > 0 {
				var userp models.User
				data_source.Db.Where("id = ?", user.Pid).First(&userp)
				if userp.Xiaoshoutuiguan == 2 {
					var tuiguang models.Tuiguang
					data_source.Db.Where("id = 2").First(&tuiguang)

					tcprice := price * float64(tuiguang.Bfb) / 100
					userpup := models.User{
						Tcprice: userp.Tcprice + tcprice,
						Price:   userp.Price + tcprice,
					}
					data_source.Db.Where("id = ?", user.Pid).Updates(&userpup)
					uprice := models.Userpricenew{
						Uid:     user.Pid,
						Price:   tcprice,
						State:   1,
						Addtime: time.Now().Unix(),
						Title:   "下级用户购买信息收到提成",
						Dqprice: userp.Price,
					}
					data_source.Db.Create(&uprice)
				}

			}

			if status == 1 {
				var fbruser models.User
				data_source.Db.Where("id = ?", procure.Uid).First(&fbruser)
				data_source.Db.Model(&models.User{}).Where("id = ?", procure.Uid).Update("dsx", fbruser.Dsx+price)

				userdsx := models.Userdsx{
					Uid:     procure.Uid,
					Price:   price,
					Title:   "用户购买,增加待生效金额",
					Addtime: time.Now().Unix(),
					Zqprice: fbruser.Dsx,
				}
				data_source.Db.Create(&userdsx)
				currentTime := time.Now()
				year, month, day := currentTime.Date()
				shijian := utils.Int64string(int64(year)) + "年" + utils.Int64string(int64(month)) + "月" + utils.Int64string(int64(day)) + "日"
				Buychenggong(fbruser.RoutineOpenid, procure.Title, shijian, utils.Int64string(int64(buyordernumbn)))
			}
		}

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    "ok",
			"msg":     "ok",
		})
		return
	}

	//var synum int64
	var buyordernum int64
	if state == 1 {

		var proderinfo models.Procureorder
		data_source.Db.Where("procureid = ?", procuresid).Where("uid = ?", uid).Where("addtime > ?", time.Now().Unix()-180).First(&proderinfo)
		if proderinfo.ID > 0 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "您的购买速度过快",
			})
			return
		}
		buyordernum = 1
		if userprice < price {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "余额不足",
			})
			return
		}

		prorder := models.Procureorder{
			Uid:        uid,
			Addtime:    time.Now().Unix(),
			Procureid:  procuresid,
			Num:        1,
			Price:      procure.Price,
			Phone:      user.Phone,
			Status:     status,
			Title:      procure.Title,
			Fbuid:      procure.Uid,
			Updatetime: time.Now().Unix(),
			State:      1,
		}
		data_source.Db.Create(&prorder)

		procureupdata := models.Procure{
			Buynum: procure.Buynum + 1,
		}
		data_source.Db.Where("id = ?", procuresid).Updates(&procureupdata)
		//data_source.Db.Model(&models.Procure{}).Where("id = ?", procuresid).UpdateColumn("buynum", gorm.Expr("buynum + 1"))
		//data_source.Db.Model(&models.Infosjb{}).Where("procureid = ?", procuresid).Where("laiyuan = 3").UpdateColumn("buynum", gorm.Expr("buynum + 1"))
		//synum = 4 - procure.Buynum - 1
	} else if state == 2 {
		buyordernum = 4 - procure.Buynum
		price = price * float64(buyordernum)
		if userprice < price {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "余额不足",
			})
			return
		}
		prorder := models.Procureorder{
			Uid:        uid,
			Addtime:    time.Now().Unix(),
			Procureid:  procuresid,
			Num:        buyordernum,
			Price:      procure.Price,
			Phone:      user.Phone,
			Status:     status,
			Fbuid:      procure.Uid,
			Title:      procure.Title,
			Updatetime: time.Now().Unix(),
			State:      1,
		}
		data_source.Db.Create(&prorder)
		//synum = 0
		data_source.Db.Model(&models.Procure{}).Where("id = ?", procuresid).Update("buynum", 4)
		//data_source.Db.Model(&models.Infosjb{}).Where("procureid = ?", procuresid).Where("laiyuan = 3").Update("buynum", 4)
	}
	//fmt.Println(price)
	//return
	userupdatetwo := models.User{
		Price: userprice - price,
		Ifbuy: 2,
	}
	data_source.Db.Where("id = ?", uid).Updates(&userupdatetwo)
	userpricenew := models.Userpricenew{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		State:   2,
		Price:   price,
		Title:   "购买信息" + procure.Title,
		Dqprice: userprice - price,
	}
	data_source.Db.Create(&userpricenew)

	if user.Pid > 0 {
		var userp models.User
		data_source.Db.Where("id = ?", user.Pid).First(&userp)
		if userp.Xiaoshoutuiguan == 2 {
			var tuiguang models.Tuiguang
			data_source.Db.Where("id = 2").First(&tuiguang)

			tcprice := price * float64(tuiguang.Bfb) / 100
			userpup := models.User{
				Tcprice: userp.Tcprice + tcprice,
				Price:   userp.Price + tcprice,
			}
			data_source.Db.Where("id = ?", user.Pid).Updates(&userpup)
			uprice := models.Userpricenew{
				Uid:     user.Pid,
				Price:   tcprice,
				State:   1,
				Addtime: time.Now().Unix(),
				Title:   "下级用户购买信息收到提成",
				Dqprice: userp.Price,
			}
			data_source.Db.Create(&uprice)
		}

	}

	if status == 1 {
		var fbruser models.User
		data_source.Db.Where("id = ?", procure.Uid).First(&fbruser)
		//data_source.Db.Model(&models.User{}).Where("id = ?", procure.Uid).UpdateColumn("dsx", gorm.Expr("dsx + ?", price))
		data_source.Db.Model(&models.User{}).Where("id = ?", procure.Uid).Update("dsx", fbruser.Dsx+price)

		userdsx := models.Userdsx{
			Uid:     procure.Uid,
			Price:   price,
			Title:   "用户购买,增加待生效金额",
			Addtime: time.Now().Unix(),
			Zqprice: fbruser.Dsx,
		}
		data_source.Db.Create(&userdsx)
		currentTime := time.Now()
		year, month, day := currentTime.Date()
		shijian := utils.Int64string(int64(year)) + "年" + utils.Int64string(int64(month)) + "月" + utils.Int64string(int64(day)) + "日"
		Buychenggong(fbruser.RoutineOpenid, procure.Title, shijian, utils.Int64string(buyordernum))
	}
	//Appaccountmodify(utils.Int64string(synum), procure.InfoId)
	//Ywdcharu(procure, user, buyordernum, price)
	var procureorderlist []models.Procureorder
	data_source.Db.Where("procureid = ?", procuresid).Where("status != 4").Find(&procureorderlist)
	var buynumupdate int64
	for _, v := range procureorderlist {
		buynumupdate = buynumupdate + v.Num
	}
	if buynumupdate >= 4 {
		data_source.Db.Model(&models.Procure{}).Where("id = ?", procuresid).Update("buynum", 4)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

func Ywdcharu(procure models.Procure, user models.User, buyordernum int64, price float64) {
	var yw_weixin models.YwWeixin
	data_source.Db.Where("unionid = ?", user.Unionid).First(&yw_weixin)

	infobuy := models.YwWeixinInfoBuy{
		InfoId:      utils.StrToInt64(procure.InfoId),
		AccountId:   yw_weixin.ID,
		AccountName: yw_weixin.Nickname,
		Ctime:       time.Now().Unix(),
		Num:         int8(buyordernum),
		Status:      1,
		Title:       procure.Title,
		Progress:    1,
	}
	data_source.Db.Create(&infobuy)

}

func Buyxiaoxiceshi(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid

	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)

	currentTime := time.Now()
	year, month, day := currentTime.Date()
	shijian := utils.Int64string(int64(year)) + "年" + utils.Int64string(int64(month)) + "月" + utils.Int64string(int64(day)) + "日"
	Buychenggong(user.RoutineOpenid, "测试", shijian, utils.Int64string(2))
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

type ProcureordersRBody struct {
	Data       []models.Procureorder `json:"data"`
	PageNo     int                   `json:"pageNo"`
	PageSize   int                   `json:"pageSize"`
	TotalCount int64                 `json:"totalCount"`
	TotalPage  int64                 `json:"totalPage"`
}

func Procureorders(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Procureorder
	res := data_source.Db.Where("fbuid = ?", uid)
	res.Model(&models.Procureorder{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)

	for k, v := range users {
		users[k].Price = v.Price * float64(v.Num)
	}

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureordersRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type ProcureordertkRBody struct {
	Data       []models.Procureordersql `json:"data"`
	PageNo     int                      `json:"pageNo"`
	PageSize   int                      `json:"pageSize"`
	TotalCount int64                    `json:"totalCount"`
	TotalPage  int64                    `json:"totalPage"`
}

func Procureordertk(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Procureordersql
	res := data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime").Joins("left join procure on procure.id = procureorder.procureid").Where("procureorder.fbuid = ?", uid).Where("procureorder.status = 3 or procureorder.status = 4 or procureorder.status = 5")
	res.Model(&models.Procureorder{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("procureorder.id desc").Find(&users)
	for k, v := range users {
		users[k].Price = v.Price * float64(v.Num)
	}
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureordertkRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type ProcurebuysRBody struct {
	Data       []models.Procureordergm `json:"data"`
	PageNo     int                     `json:"pageNo"`
	PageSize   int                     `json:"pageSize"`
	TotalCount int64                   `json:"totalCount"`
	TotalPage  int64                   `json:"totalPage"`
}

func Procurebuys(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	status := request.Status
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Procureordergm
	res := data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.content, procure.phone as procurephone, procure.name as procurename").Joins("left join procure on procure.id = procureorder.procureid").Where("procureorder.uid = ?", uid)
	if status > 0 {
		res = res.Where("status = ?", status)
	}
	res.Model(&models.Procureorder{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("addtime desc").Find(&users)

	for k, v := range users {
		users[k].Phone = v.Procurephone
	}

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcurebuysRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procuresqtk(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	procureorderid := request.Procureorderid

	orupd := models.Procureorder{
		Status:     3,
		Tktime:     time.Now().Unix(),
		Tuikuan:    "3次无法沟通",
		Updatetime: time.Now().Unix(),
	}

	data_source.Db.Where("id = ?", procureorderid).Updates(&orupd)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Procuretksh(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	procureorderid := request.Procureorderid
	state := request.State

	var porder models.Procureorder
	data_source.Db.Where("id = ?", procureorderid).First(&porder)
	if porder.Status == 4 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "无法退款",
		})
		return
	}

	if state == 1 {
		pro := models.Procureorder{
			Status:     4,
			Updatetime: time.Now().Unix(),
		}
		data_source.Db.Where("id = ?", procureorderid).Updates(&pro)
		//var porder models.Procureorder
		//data_source.Db.Where("id = ?", procureorderid).First(&porder)
		price := porder.Price * float64(porder.Num)

		var user_info models.User
		data_source.Db.Where("id = ?", porder.Uid).First(&user_info)
		data := Appaccountuser(user_info.Unionid)
		//fmt.Println(data)
		userprice := utils.StrToFloat64(data.User.Money) + price
		r := Appaccountmoney(user_info.Unionid, "退款成功", "1", price)
		if r.Status == 1 {
			data_source.Db.Model(&models.User{}).Where("id = ?", porder.Uid).Update("price", userprice)
			data_source.Db.Model(&models.User{}).Where("id = ?", porder.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", price))
			data_source.Db.Model(&models.Procure{}).Where("id = ?", porder.Procureid).UpdateColumn("buynum", gorm.Expr("buynum - ?", porder.Num))
			data_source.Db.Model(&models.Procureorder{}).Where("id = ?", procureorderid).Update("tkdaozhang", 2)
		}

	} else if state == 2 {
		pro := models.Procureorder{
			Status:     5,
			Updatetime: time.Now().Unix(),
		}
		data_source.Db.Where("id = ?", procureorderid).Updates(&pro)
		//data_source.Db.Model(&models.Procureorder{}).Where("id = ?", procureorderid).Update("status", 5)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procurezdkk(ctx *gin.Context) {

	dqtime := time.Now().Unix()
	qitianqian := dqtime - 86400*7

	var orders []models.Procureorder
	data_source.Db.Where("status = 1").Where("addtime < ?", qitianqian).Where("daozhang != 2").Find(&orders)
	//data_source.Db.Where("status = 1").Where("addtime < ?", qitianqian).Find(&orders)

	for _, v := range orders {
		var user models.User
		data_source.Db.Where("id = ?", v.Fbuid).First(&user)

		if user.Dsx >= v.Price*float64(v.Num) {

			userdsx := models.Userdsx{
				Uid:     v.Fbuid,
				Price:   v.Price * float64(v.Num),
				Title:   "自动提现待生效金额减少",
				Addtime: time.Now().Unix(),
				Zqprice: user.Dsx,
			}
			data_source.Db.Create(&userdsx)

			data_source.Db.Model(&models.User{}).Where("id = ?", v.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", v.Price*float64(v.Num)))
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Fbuid).UpdateColumn("yue", gorm.Expr("yue + ?", v.Price*float64(v.Num)))

			pro := models.Procureorder{
				Status:     2,
				Updatetime: time.Now().Unix(),
				Daozhang:   2,
				//Tcprice:    tcprice,
				Pid: user.Pid,
			}
			data_source.Db.Where("id = ?", v.ID).Updates(&pro)
			//data_source.Db.Model(&models.Procureorder{}).Where("id = ?", v.ID).Update("daozhang", 2)

			uprice := models.Userprice{
				Uid:     v.Fbuid,
				Price:   v.Price * float64(v.Num),
				State:   1,
				Addtime: time.Now().Unix(),
				Title:   "商机卖出",
			}
			data_source.Db.Create(&uprice)

			dzprice := utils.FloatToStr64(v.Price*float64(v.Num)) + "元"

			Yuertongzhi(user.RoutineOpenid, dzprice)

		}

	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

func Procurezdkk5(ctx *gin.Context) {

	dqtime := time.Now().Unix()
	qitianqian := dqtime - 86400*7
	var orders []models.Procureorder
	data_source.Db.Where("status = 5").Where("addtime < ?", qitianqian).Where("daozhang != 2").Find(&orders)
	//var tuiguang models.Tuiguang
	//data_source.Db.Where("id = 1").First(&tuiguang)
	for _, v := range orders {

		var user models.User
		data_source.Db.Where("id = ?", v.Fbuid).First(&user)
		if user.Dsx >= v.Price*float64(v.Num) {
			userdsx := models.Userdsx{
				Uid:     v.Fbuid,
				Price:   v.Price * float64(v.Num),
				Title:   "自动提现待生效金额减少",
				Addtime: time.Now().Unix(),
				Zqprice: user.Dsx,
			}
			data_source.Db.Create(&userdsx)

			data_source.Db.Model(&models.User{}).Where("id = ?", v.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", v.Price*float64(v.Num)))
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Fbuid).UpdateColumn("yue", gorm.Expr("yue + ?", v.Price*float64(v.Num)))

			pro := models.Procureorder{
				Daozhang:   2,
				Updatetime: time.Now().Unix(),
				Pid:        user.Pid,
				//Tcprice:    tcprice,
			}
			data_source.Db.Where("id = ?", v.ID).Updates(&pro)
			//data_source.Db.Model(&models.Procureorder{}).Where("id = ?", v.ID).Update("status", 2)

			uprice := models.Userprice{
				Uid:     v.Fbuid,
				Price:   v.Price * float64(v.Num),
				State:   1,
				Addtime: time.Now().Unix(),
				Title:   "商机卖出",
			}
			data_source.Db.Create(&uprice)
		}

	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

func Procurezdkkcs(ctx *gin.Context) {

	//var users1 []models.Procureordersql
	//data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime, procure.uid as fbuid").Joins("left join procure on procure.id = procureorder.procureid").Where("procure.uid = 19465").Where("procure.id <= 3554").Find(&users1)
	var orders []models.Procureorder
	data_source.Db.Where("fbuid=14491").Where("status=1").Find(&orders)
	var price float64
	for _, v := range orders {
		price = price + v.Price*float64(v.Num)
	}
	fmt.Println(price)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    orders,
		"msg":     "ok",
	})
	return

}

func Chulisjb(ctx *gin.Context) {

	var orders []models.Infosjb
	data_source.Db.Find(&orders)
	var names []string

	for _, v := range orders {
		var classifysjb models.Classifysjsjb
		data_source.Db.Where("id = ?", v.Classifysjbid).First(&classifysjb)
		var classifysjb2 models.Classifysjsjb2
		data_source.Db.Where("name = ?", classifysjb.Name).First(&classifysjb2)
		data_source.Db.Model(&models.Infosjb{}).Where("id = ?", v.ID).Update("classifysjbid", classifysjb2.ID)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    names,
		"msg":     "ok",
	})
	return

}
